<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: File.php 240 2011-06-13 13:02:06Z beimuaihui $
 */
class Baogg_File_Html extends Baogg_File
{
	static function genFile($dir,$filename,$content='')
	{
		self::mkdir(BAOGG_UPLOAD_DIR.$dir);
		$filename=self::fixFileName($filename);
		
		file_put_contents(BAOGG_UPLOAD_DIR.$dir.$filename, $content);

		return BAOGG_UPLOAD_URL.$dir.$filename;
	}
	static function genFiles($dir,$filenames=array(),$urls=array())
	{
		self::mkdir(BAOGG_UPLOAD_DIR.$dir);
		$contents=self::multiGet($urls);
		foreach($filenames as $k=>$filename){
			self::genFile($dir, $filename,$contents[$k]);
		}		
	
		return $filenames;
	}
	static function multiGet($urls=array(),$fixUrlName=true)
	{
		$res=array();
		// Create get requests for each URL
		$mh = curl_multi_init();
		foreach($urls as $i => $url)
		{
			$ch[$i] = curl_init();
			curl_setopt($ch[$i], CURLOPT_URL, $url);
			curl_setopt($ch[$i], CURLOPT_HEADER, 0);
			curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 1);
			curl_multi_add_handle($mh, $ch[$i]);
		}

		// Start performing the request
		$active = null;
		do {
			$execReturnValue = curl_multi_exec($mh, $active);
		} while ($execReturnValue == CURLM_CALL_MULTI_PERFORM);
		// Loop and continue processing the request
		while ($active && $execReturnValue == CURLM_OK) {
			// Wait forever for network
			$numberReady = curl_multi_select($mh);
			if ($numberReady != -1) {
				// Pull in any new data, or at least handle timeouts
				do {
					$execReturnValue = curl_multi_exec($mh, $active);
				} while ($execReturnValue == CURLM_CALL_MULTI_PERFORM);
			}
		}

		// Check for any errors
		/* if ($execReturnValue != CURLM_OK) {
			trigger_error("Curl multi read error $execReturnValue\n", E_USER_WARNING);
		} */

		// Extract the content
		foreach($urls as $i => $url)
		{
			// Check for errors
			$curlError = curl_error($ch[$i]);
			if($curlError == "") {
				$res[$i] = curl_multi_getcontent($ch[$i]);
			} else {
				$res[$i] ="";//print "Curl error on handle $i: $curlError\n";
			}
			// Remove and close the handle
			curl_multi_remove_handle($mh, $ch[$i]);
			curl_close($ch[$i]);
		}
		// Clean up the curl_multi handle
		curl_multi_close($mh);
		
		
		//replace url like href="../test.css" and so on
		if($fixUrlName){
			foreach((array)$res as $k=>$v){
				$baseUrl=$urls[$k];
				$res[$k]=preg_replace_callback("/(\shref=[\"'])([\w\.\/]+)([\"'][\s\/>])/mi", create_function('$matches','return $matches[1].Baogg_File::fixUrlName($matches[2], "'.$baseUrl.'").$matches[3];'), $v);
				$res[$k]=preg_replace_callback("/(\ssrc=[\"'])([\w\.\/]+)([\"'][\s\/>])/mi", create_function('$matches','return $matches[1].Baogg_File::fixUrlName($matches[2], "'.$baseUrl.'").$matches[3];'), $v);
			}
		}
		// Print the response data
		return $res;
	}
}